package com.cskaoyan.service;

import com.cskaoyan.bean.Ad;
import com.cskaoyan.bean.AdExample;
import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.QueryParams;
import com.cskaoyan.mapper.AdMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AdServiceImpl implements AdService {
    @Autowired
    AdMapper adMapper;

    @Override
    @Transactional
    public Ad createAd(Ad ad) {
        // 初次创建广告 创建时间和 更新时间一直 所以创建一个time
        Date time = new Date(System.currentTimeMillis());
        // 设置addTime 和 updateTime
        ad.setAddTime(time);
        ad.setUpdateTime(time);
        // 设置id
        ad.setId(adMapper.selectLastInsert() + 1);
        // 往数据库插入数据
        adMapper.insertSelective(ad);
        return ad;
    }

    @Override
    public Ad updateAd(Ad ad) {
        // 设置更新数据的时间
        ad.setUpdateTime(new Date(System.currentTimeMillis()));
        // 设定更新数据的行数限制为id = ?
        AdExample adExample = new AdExample();
        AdExample.Criteria criteria = adExample.createCriteria();
        criteria.andIdEqualTo(ad.getId());
        // 更新数据

        adMapper.updateByExample(ad, adExample);

        return ad;
    }

    @Override
    public void deleteAd(Ad ad) {
        //将逻辑删除标识符置true
        ad.setDeleted(true);
        //是用更新接口更新
        updateAd(ad);
    }

    @Override
    public BaseData AdvertList(QueryParams params) {
        // 设置分页
        PageHelper.startPage(params.getPage(), params.getLimit());

        AdExample adExample = new AdExample();
        AdExample.Criteria criteria = adExample.createCriteria();
        // 设置值查询未被删除的广告
        criteria.andDeletedEqualTo(false);

        // 设置排序字段和排序方式
        adExample.setOrderByClause(params.getSort() + " " + params.getOrder());
        // 获取的广告列表
        List<Ad> ads = adMapper.selectByExample(adExample);

        PageInfo<Ad> pageInfo = new PageInfo<>(ads);
        // 获取total
        Long total = adMapper.countByExample(null);

        return new BaseData(ads,total);
    }
}
